package com.leonzx.base.controller.userpermission;

import com.leonzx.base.controller.base.BaseController;
import com.leonzx.base.entity.system.Menu;
import com.leonzx.base.entity.system.MenuRole;
import com.leonzx.base.entity.system.User;
import com.leonzx.base.entity.system.UserMenuTemp;
import com.leonzx.base.service.system.*;
import com.leonzx.base.utils.Constants;
import com.leonzx.base.utils.CronDateUtils;
import com.leonzx.base.utils.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Author:梁亮
 * @Description:
 * @Date: 2018/6/11 17:27
 */
@RestController
@RequestMapping("/ajax/userpermission/menu")
public class AjaxMenuController extends BaseController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private MenuRoleService menuRoleService;
    @Autowired
    private UserMenuTempService userMenuTempService;
    @Autowired
    private MenuDataService menuDataService;
    @Autowired
    private JobService jobService;
    @Autowired
    private UserService userService;


    /**
     * @return
     */
    @RequestMapping("/tree")
    @RequiresPermissions("/menu/tomenu")
    public Map<String, Object> menuTree() {
        Map<String, Object> result = getMap();
        try {
            List<Map<String, Object>> baseMenus = menuService.findAllTree();
            result.put("datas", baseMenus);
            addSuccessMessage(result, "获取菜单数据成功");
        } catch (Exception e) {
            logger.error("获取菜单数据失败", e);
            addFailMessage(result, "获取菜单数据失败");
        }
        return result;
    }

    @RequestMapping("/rolemenutree")
    @RequiresPermissions("/menu/tomenu")
    public Map<String, Object> menuTree(String roleId) {
        Map<String, Object> result = getMap();
        try {
            List<Map<String, Object>> baseMenus = menuService.findAllTreeChecked(roleId);
            result.put("datas", baseMenus);
            addSuccessMessage(result, "获取菜单数据成功");
        } catch (Exception e) {
            logger.error("获取菜单数据失败", e);
            addFailMessage(result, "获取菜单数据失败");
        }
        return result;
    }

    /**
     * 查询我拥有的权限,排除当前人有的权限，然后可分配临时
     *
     * @param userId
     * @return
     */
    @RequestMapping("/usermenutemptree")
    @RequiresPermissions("/menu/tomenu")
    public Map<String, Object> usermenutemptree(String userId) {
        Map<String, Object> result = getMap();
        try {
            List<Map<String, Object>> menus = menuService.findAllTreeHad(currentUser().getId(), userId);
            if (menus.size() == 0) {
                addSuccessMessage(result, "没有可分配的临时权限");
            } else {
                result.put("datas", menus);
                addSuccessMessage(result, "获取数据成功");
            }
        } catch (Exception e) {
            logger.error("获取当前人拥有权限失败", e);
            addFailMessage(result, "获取权限失败，请联系管理员");
        }
        return result;
    }

    /**
     * 无子菜单情况下，删除
     *
     * @param id
     * @return
     */
    @RequestMapping("/del")
    @RequiresPermissions("/menu/tomenu")
    public Map<String, Object> delMenu(String id) {
        Map<String, Object> result = getMap();
        try {
            List<Menu> menus = menuService.findMenuByParentId(id);
            if (menus.size() > 0) {
                addFailMessage(result, "请先删除子菜单");
            } else {
                Menu menu = new Menu();
                menu.setId(id);
                menu.setState(0);
                menuService.updateMenu(menu);
                addSuccessMessage(result, "删除成功");
            }
        } catch (Exception e) {
            logger.error("节点删除失败", e);
            addFailMessage(result, "节点删除失败");
        }
        return result;
    }

    /**
     * 保存临时人员权限菜单
     */
    @RequestMapping("/usermenutempsave")
    @RequiresPermissions("/userpermission/user/list")
    public Map<String, Object> rolemenusave(String userId, String menuIds, Date expireTime) {
        Map<String, Object> result = getMap();
        try {
            String[] menuId = menuIds.split(",");
            for (int i = 0; i < menuId.length; i++) {
                UserMenuTemp userMenuTemp = new UserMenuTemp();
                userMenuTemp.setMenuId(menuId[i]);
                userMenuTemp.setUserId(userId);
                userMenuTemp.setCreateUserId(currentUser().getId());
                userMenuTemp.setState(Constants.STATE_VAILD);
                userMenuTemp.setExpireTime(expireTime);
                userMenuTemp.setCreateTime(new Date());
                userMenuTempService.saveOrUpdate(userMenuTemp);
                addSuccessMessage(result, "角色分配权限成功");

            }
            //清理人员缓存倒计时任务
            String jobName ="com.leonzx.base.config.quartz.job.UserReflash";
            String jobClassName = "com.leonzx.base.config.quartz.job.UserReflash";
            String jobGroupName = UUIDUtils.getUUID();
            String description = "人员临时权限超时清缓存";
            String cronExpression = CronDateUtils.getCron(expireTime);
            Map<String, String> datas = new HashMap<>();
            User user  = userService.getUserById(userId);
            String userJson = gson.toJson(user);
            datas.put("user",userJson);
            jobService.jobAdd(jobName,jobClassName,jobGroupName,description,cronExpression,datas);
        } catch (Exception e) {
            logger.error("角色分配权限失败", e);
            addFailMessage(result, "角色分配权限失败");
        }
        return result;
    }

    /**
     * 获取父菜单
     *
     * @return
     */
    @RequestMapping("/getParentAndSonMenu")
    public Map<String, List<Menu>> findParentMenus() {
        Map<String, List<Menu>> map = new HashMap<>();
        try {
            List<Menu> menus = menuService.getRootMenuByIds(currentUser().getId());
            map.put("menus", menus);
        } catch (Exception e) {
            logger.error("获取菜单失败", e);
        }
        return map;
    }

    /**
     * @return
     */
    @RequestMapping("/indexMenuZtree")
    public Map<String, Object> indexMenuZtree() {
        Map<String, Object> result = getMap();
        try {
            List<Map<String, Object>> menusMap = menuService.ztreeGetRootMenuByIds(currentUser().getId());
            result.put("datas", menusMap);
            addSuccessMessage(result, "获取菜单数据成功");
        } catch (Exception e) {
            logger.error("获取菜单数据失败", e);
            addFailMessage(result, "获取菜单数据失败");
        }
        return result;
    }

    /**
     * 保存菜单编辑,更新或者插入
     *
     * @param menu
     * @return
     */
    @RequestMapping("/update")
    @RequiresPermissions("/menu/tomenu")
    public Map<String,Object> saveOrUpdate(Menu menu) {
        Map<String,Object> result = getMap();
        try{
            if (StringUtils.isNotBlank(menu.getId())) {
                menuService.updateMenu(menu);
                addSuccessMessage(result,"修改成功");
            } else {
                menu.setState(1);
                menu.setCreateUserId(currentUser().getId());
                if (StringUtils.isNotBlank(menu.getParentId())){
                   Menu menu1 = menuService.findById(menu.getParentId());
                   if (StringUtils.isNotBlank(menu1.getParentId())){
                       Menu menu2 =menuService.findById(menu1.getParentId());
                       if (StringUtils.isNotBlank(menu2.getParentId())){
                           addFailMessage(result,"菜单最多三层");
                       }else{
                           menuService.saveMenu(menu);
                           addSuccessMessage(result,"提交成功");
                       }
                   }else{
                       menuService.saveMenu(menu);
                       addSuccessMessage(result,"提交成功");
                   }
                }else{
                    menuService.saveMenu(menu);
                    addSuccessMessage(result,"提交成功");
                }
            }
        }catch (Exception e){
            logger.error("编辑菜单失败",e);
            addFailMessage(result,"提交失败，请联系管理员");
        }
        return result;
    }

    @RequestMapping("/saveCustomMenu")
    public Map<String, Object> saveCustomMenu(String json) {
        Map<String, Object> result = getMap();
        try {
            menuDataService.saveMenuData(json, currentUser().getId());
            result.put("msg", "修改成功");
            addSuccessMessage(result, "修改成功");
        } catch (Exception e) {
            logger.error("修改失败", e);
            addFailMessage(result, "修改失败");
        }
        return result;
    }
}
